<template lang='pug'>
  Modal.mail-detail(v-model="show" fullscreen title="邮件详情" :class="loading?'ov-hide':''")
    Spin.z-99(v-if="loading" size="large" fix)
    .theme {{mailInfo.theme}}
    .from.mb-5
      .name 发件人：{{mailInfo.name}}
      .time
        Icon.mr-5(type="md-time" size="18")
        | {{sendTime}}
    .user-list.mb-20
      span 收件人：
      span.item.mr-10(v-for="(item,index) in mailInfo.userList" :key="index") {{item.name}};
    List.mail-attr-list.mb-50(v-if="mailInfo.attaList && mailInfo.attaList.length > 0" border)
      .font-16.font-weight(slot="header") 附件（{{mailInfo.attaList.length}}个）
      ListItem(v-for="item in mailInfo.attaList" :key="item.id")
        i.iconfont.icon-fujian
        span {{item.name}}
        span.down(@click="download(item.id, item.name)") 下载
    Divider
    .mail-content.mb-50(v-html="mailInfo.content")
    .mail-reply
      .line.mb-30
        span 邮件回复
      .reply-list.mb-20
        //- .item(v-for="item in replyList" :key="item.mailId")
        //-   .name {{item.name}}的回复：
        //-   .content {{item.content}}
        Timeline
          TimelineItem(v-for="item in replyList" :key="item.mailId")
            .reply-item
              .name {{item.name}}的回复：
              .content(v-html="item.content")
            .attr-list
              .attr-item(v-for="i in item.attaList")
                i.iconfont.icon-fujian
                span {{i.name}}
                span.down(@click="download(i.id, i.name)") 下载
    template(v-if="replyShow")
      .mail-text(v-if="textHide" @click="textHide = false") 点击此处，可以快捷回复...
      .mail-reply-form(v-else)
        .mb-5
          //- Input.input-has-border(v-model="formData.content" type="textarea" autofocus :autosize="{minRows: 3,maxRows: 6}" @on-change="contentChange")
          editor(ref="editor" :value="formData.content")
          .font-12(v-show="notEmpty" :style="{'color': '#ed4014'}") 请填写回复内容
        .mb-5
          Upload(
            :show-upload-list="false"
            :multiple="true"
            :action="uploadBaseUrl + '/MailManage/Upload?categoryName=邮件管理'" 
            :on-success="attachmentsBefore" 
          )
            .cursor-pointer
              i.font-18.iconfont.icon-fujian
              span 添加附件
          template(v-for="(item, index) in file")
            .my-tag.mr-20
              .my-tag-inner {{item.Name}}
              .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFile(item.Id)")
        div
          Button(type="info" @click="submitBtn") 发送
          Button.ml-15(@click="textHide = true") 取消
    template(slot="footer")
      Button(@click="show = false") 关闭
</template>

<script>
import MailApi from "../service.js";
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import Editor from '_c/editor'
import config from '@/config';
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: "mail-detail",
  props: {
    loading: Boolean,
    detailData: Array,
    replyShow: Boolean
  },
  data() {
    return {
      show: false,
      uploadBaseUrl: baseUrl,
      notEmpty: false,
      // mailInfo: {},
      textHide: true,
      formData: {
        theme: '',
        originalId: '',
        name: '',
        fromId: '',
        attaIdList: [],
        content: '',
        toIdList: [],
      },
      // replyList: [],
      file: []
    }
  },

  components: {
    Editor
  },

  computed: {
    mailInfo () {
      if (this.detailData[0]) {
        return this.detailData[0]
      } else {
        return []
      }
    },
    replyList () {
      return this.detailData.filter((item,index) => {
        return index > 0
      })
    },
    sendTime () {
      if (this.detailData[0]) {
        let date;
        let m2=this.$moment();  //当下时间
        let m1=this.$moment(this.detailData[0].createdOn);
        let du = this.$moment.duration(m2 - m1, 'ms');   //做差
        let days = du.get('days');
        let hours = du.get('hours');
        let mins = du.get('minutes');   
        let ss = du.get('seconds'); 
        // console.log(days,hours,mins,ss)
        if (days>0) {
          date=this.$moment(this.detailData[0].createdOn).format("YYYY年MM月DD日");
          return date
        }else if(hours>0){
          return hours+'小时前'
        }else{
          return mins+'分钟前'
        }
      } else {
        return ''
      }
    },
  },

  beforeMount() {},

  mounted() {
    console.log(this.$store.state.user)
    // this.getDetail()
  },

  methods: {
    ...mapActions([
      'handleInbox',
      'handleOutbox'
    ]),
    openModal () {
      this.show = true
      this.textHide = true
    },
    download (id,name) {
      MailApi.downloadAttr({
        id: id
      }).then(res => {
        console.log(res)
        let fileName = name
        let blob = new Blob([res.data], { type: 'application/octet-stream' })
        if ('download' in document.createElement('a')) {
          let objectUrl = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.download = fileName
          link.href = objectUrl
          link.click()
        } else {
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    attachmentsBefore (response, file, fileList) {
      console.log('@@@@@@@@@@@@')
      console.log(response, file, fileList)
      this.file.push(response.Data)
      this.formData.attaIdList.push(response.Data.Id)
    },
    deleteFile (id) {
      MailApi.DeleteAnnex({
        id: id
      }).then(res => {
        this.file = this.file.filter(item => {
          return item.Id !== id
        })
        this.formData.attaIdList = this.formData.attaIdList.filter(item => {
          return item === id
        })
      })
    },
    // 提交
    submitBtn () {
      // this.formData.originalId = ''
      this.formData.content = this.$refs.editor.editor.txt.html()
      if (this.formData.content) {
        this.addMail()
      } else {
        this.notEmpty = true
      }
    },
    // 回复
    addMail () {
      let userId = this.$store.state.user.userId
      let index = this.detailData.length - 1
      this.formData.name = this.$store.state.user.userName;
      this.formData.fromId = userId;
      this.formData.theme = this.detailData[index].theme
      this.formData.originalId = this.detailData[index].mailId
      this.detailData[index].userList.forEach(item => {
        if (item.id != userId) {
          this.formData.toIdList.push(item.id)
        }
      })
      this.formData.toIdList.push(this.detailData[index].fromId)
      console.log(this.formData)

      MailApi.addMail(this.formData).then(res => {
        console.log(res)
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.formData = {
            theme: '',
            originalId: '',
            name: '',
            fromId: '',
            attaIdList: [],
            content: '',
            toIdList: [],
          }
          this.file = []
          this.$emit('get-list')
          this.show = false
          this.handleOutbox(true)
          this.handleInbox(true)
        } else {
          this.$Message.error(res.data.message)
        }
      })
    },
    contentChange (val) {
      if (val) {
        this.notEmpty = false
      } else {
        this.notEmpty = true
      }
    }
  },

  watch: {}
};
</script>
<style lang="less">
.mail-attr-list{
  .ivu-list-header{
    background-color: #f2f2f2;
  }
  .ivu-list-items{
    padding-left: 38px;
    .ivu-list-item{
      padding-left: 0;
      padding-right: 70px;
      position: relative;
      .iconfont{
        position: absolute;
        top: 10px;
        left: -24px;
        color: #f25149;
        font-size: 18px;
      }
      .down{
        color: #0dc2ff;
        // position: absolute;
        // top: 12px;
        // right: 30px;
        margin-left: 20px;
        cursor: pointer;
      }
    }
  }
}
.mail-detail{
  &.ov-hide{
    .ivu-modal-body{
      overflow: hidden !important;
    }
  }
  .ivu-modal-wrap {
    top: 5%;
    bottom: 5%;
    left: 5%;
    right: 5%;
  }
  .reply-list{
    .ivu-timeline-item-tail{
      border-color: #0dc2ff;
      left: 7px;
    }
    .ivu-timeline-item-head.ivu-timeline-item-head-blue{
      width: 15px;
      height: 15px;
      background-color: #0dc2ff;
      border: 4px solid #fff;
    }
  }
}
.mail-content{
  th,td{
    border: 1px solid #eee;
    margin: -1px;
  }
  img{
    width: auto;
  }
}
</style>

<style lang='less' scoped>
.z-99{
  z-index: 99;
}
.mail-detail{
  background-color: #fff;
  min-height: 100%;
  .theme{
    font-size: 30px;
    margin-bottom: 20px;
    color: #000;
  }
  .from{
    display: flex;
    justify-content: space-between;
    align-items: center;
    .time{
      color: #b2b2b2;
    }
  }
  .mail-content{
    font-size: 16px;
    line-height: 36px;
    img{
      width: auto;
    }
  }
  .mail-reply{
    .line{
      width: 300px;
      text-align: center;
      position: relative;
      span{
        display: inline-block;
        width: 80px;
        background-color: #fff;
        position: relative;
        z-index: 9;
      }
      &:after{
        content: '';
        width: 100%;
        border-bottom: 1px dotted #0dc2ff;
        position: absolute;
        top: 50%;
        margin-top: -1px;
        left: 0;
      }
    }
  }
  .reply-list{
    .reply-item{
      display: flex;
      align-items: flex-start;
      .name{
        white-space:nowrap;
      }
    }
  }
  .mail-text{
    width: 100%;
    height: 48px;
    line-height: 48px;
    padding: 0 30px;
    color: #b2b2b2;
    border-radius: 4px;
    box-shadow: 0px 0px 5px rgba(0,0,0,.18) inset;
    cursor: pointer;
  }
  .mail-reply-form{
    .cursor-pointer{
      display: flex;
      align-items: center;
      color: #0bc2ff;
    }
  }
  .attr-list{
    .attr-item{
      width: 100%;
      height: 30px;
      line-height: 30px;
      border-radius: 4px;
      margin-top: 10px;
      position: relative;
      background-color: #f2f2f2;
      padding: 0 10px;
      .iconfont{
        color: #f25149;
        margin-right: 5px;
      }
      .down{
        color: #0dc2ff;
        position: absolute;
        top: 0px;
        right: 20px;
        cursor: pointer;
      }
    }
  }
}
</style>